package com.kobeliu.api.interceptor;

import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.exceptions.GraceException;
import com.kobeliu.exceptions.MyCustomException;
import com.kobeliu.result.ResponseStatusEnum;
import com.kobeliu.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    /**
     * 进入到controller层之前
     * @param request
     * @param response
     * @param handler
     * @return true 放行  false 拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userIp = IPUtil.getRequestIp(request);
        if(redis.keyIsExist(MOBILE_SMSCODE+":"+userIp)){

            log.error("短信发送频率较快，请稍后再试。。。。。");
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }

        return true;
    }

    /**
     * controller层之后，还没有渲染画面
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
